package cn.biplam.back.services.snr;

import java.rmi.Naming;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import cn.biplam.back.jda.Jda;
import cn.biplam.common.bean.sqlengine.Sql;
import cn.biplam.common.client.DbResource;
import cn.biplam.common.tools.DEBUG;
import cn.biplam.common.wrapper.ErrorMessage;
import cn.biplam.common.wrapper.sqlresult.SqlResult;

/**
 * 服务注册
 * @author 	WangSong 2009-3-11 上午09:13:36
 * @version 1.0
 */
public class ServiceNameRegister implements Runnable {
	
	private static SqlResult mSqlResult;
	private static final String tableName = "sys_services";
	
	/**
	 * 服务注册
	 * @throws ErrorMessage 
	 */
	private static void register() throws ErrorMessage{
		if(mSqlResult==null){
			getRefisterInfo();//取服务信息
		}
		register(mSqlResult);//注册
	}
	
	/**
	 * @throws ErrorMessage 
	 * 	 取需注册的服务信息
	 */
	private static void getRefisterInfo() throws ErrorMessage {
		
		DbResource mDbResource = new DbResource(DbResource.SNR);
		Jda mJda = new Jda(mDbResource);
		StringBuffer sql = new StringBuffer();
		sql.append(" select t.id,t.service_name,t.service_ip,  ");
		sql.append("        t.service_port,t.service_class     ");
		sql.append("   from ");
		sql.append(tableName);
		sql.append(" t ");
		sql.append("  where t.service_able = 1                 ");
		sql.append("   order by szfy_id                        ");
		Sql mSql = new Sql(sql.toString());
		mSqlResult = mJda.executeSelect(mSql);
	}
	
	
	/**
	 * 服务注册
	 * @param 	mSqlResult  需要注册的结果集
	 * @throws ErrorMessage 
	 */
	private static void register(SqlResult mSqlResult) throws ErrorMessage {
		
		if(mSqlResult==null || mSqlResult.size()==0){
			throw new ErrorMessage("Service list is null!");
		}
		
		String serviceClass = null; //注册的服务类
		String serviceIp = null;   	//ip地址
		int servicePort = 0;        //端口
		String serviceName = null;	//服务名

		serviceIp = mSqlResult.get(0, "service_ip");
		servicePort = Integer.parseInt(mSqlResult.get(0, "service_port"));
		//获取服务注册表
    	Registry r = null;
    	try {
			r = LocateRegistry.getRegistry(serviceIp);
		} catch (RemoteException e) {
			throw new ErrorMessage(e,"LocateRegistry get failed!");
		}
		if(r!=null){
			try {
				r = LocateRegistry.createRegistry(servicePort);
			} catch (RemoteException e) {
				throw new ErrorMessage(e,"LocateRegistry create failed!");
			}
		}else{
			throw new ErrorMessage("Can't initialize Registry!");
		}
		
		for(int i=0;i<mSqlResult.size();i++){
			
			serviceName = mSqlResult.get(i, "service_name");
			serviceClass = mSqlResult.get(i, "service_class");

			//注册服务
			Class<?> mClass = null;
			try {
				mClass = Class.forName(serviceClass);
			} catch (ClassNotFoundException e) {
				throw new ErrorMessage(e,serviceClass);
			}
			
			Remote instance = null;
			//获取Remote实例
			try {
				instance=(Remote) mClass.newInstance();
			} catch (Exception e) {
				throw new ErrorMessage(e,"Get (Remote)Instance Failed:"+serviceClass);
			}
			
			//绑定服务
			try {
				Naming.rebind("rmi://"+serviceIp+":"+servicePort+"/"+serviceName,instance);
			} catch (Exception e) {
				throw new ErrorMessage(e,"Naming.rebind error:"+serviceClass);
			} 
			//在控制台输出注册信息
			DEBUG.println("服务注册信息 ："+serviceName+" run successful "+servicePort);
		}
	}
	
	/**
	 * 实现runable的run方法
	 */
	public void run(){   
		try {
			register();
		} catch (ErrorMessage e) {
			DEBUG.println("【SNR Error】 Service Register failed! ");
			e.printStackTrace();
		}   
	}
}
